package com.pro01.backend.controller;

import com.pro01.backend.pojo.PageResult;
import com.pro01.backend.pojo.PointLog;
import com.pro01.backend.pojo.Result;
import com.pro01.backend.pojo.UserPoint;
import com.pro01.backend.service.PointService;
import com.pro01.backend.utils.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/users/me/points")
public class PointController {

    @Autowired
    private PointService pointService;

    // 用户查看总积分
    @GetMapping
    public Result<UserPoint> getMyPoints(HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request);
            UserPoint point = pointService.getUserPoints(userId);
            return Result.success(point);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询积分失败：" + e.getMessage());
        }
    }

    // 用户查看积分明细
    @GetMapping("/logs")
    public Result<PageResult<PointLog>> getMyPointLogs(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request);
            PageResult<PointLog> pageResult = pointService.getUserPointLogs(userId, pageNum, pageSize);
            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询积分记录失败：" + e.getMessage());
        }
    }

    // 用户查看积分排行榜
    @GetMapping("/leaderboard")
    public Result<Map<String, Object>> getPointLeaderboard(HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request); // 登录用户 ID
            Map<String, Object> result = pointService.getPointLeaderboardWithSelf(userId);
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取排行榜失败：" + e.getMessage());
        }
    }


}
